package com.hb.unic.core.async.threadpool;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import lombok.extern.slf4j.Slf4j;

/**
 * 线程池操作类
 *
 * @since v1.0，2023/8/27 12:24，create by Mr.Huang.
 */
@Slf4j
public abstract class BaseThreadPoolOperation {

    /**
     * 线程池
     */
    private ThreadPoolExecutor executor;

    /**
     * 创建线程池对象
     *
     * @return 结果
     */
    protected ThreadPoolExecutor createExecutor(int corePoolSize, int maxPoolSize, int keepAliveSeconds,
        int queueCapacity, String threadNamePrefix, RejectedExecutionHandler rejectedExecutionHandler) {
        executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(queueCapacity),
            new ThreadFactoryBuilder().setNameFormat(threadNamePrefix).build(), rejectedExecutionHandler);
        log.info("ThreadPool created: {}", threadNamePrefix);
        return executor;
    }

    /**
     * 获取线程池对象
     * 
     * @return 线程池
     */
    public ThreadPoolExecutor getExecutor() {
        return executor;
    }

    /**
     * 提交任务
     * 
     * @param runnables 任务列表
     */
    public void submitAll(Runnable... runnables) {
        for (Runnable runnable : runnables) {
            executor.submit(runnable);
        }
    }

    /**
     * 提交任务
     * 
     * @param callables 任务列表
     * @return 结果
     */
    public <V> List<Future<V>> submitAll(Callable<V>... callables) {
        List<Future<V>> futureList = new LinkedList<>();
        for (Callable<V> callable : callables) {
            futureList.add(executor.submit(callable));
        }
        return futureList;
    }

}
